<?php

namespace App\Http\Middleware\Applet;

use App\Kuafu\Common\Enum\CommonCodeEnum;
use App\Kuafu\Common\Exceptions\CommonException;
use App\Kuafu\Dashboard\Service\PosOnlineService;
use App\Kuafu\Order\Enum\OrderCodeEnum;
use App\Kuafu\Order\Exceptions\OrderException;
use App\Kuafu\Shop\Enum\CodeEnum;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Service\ShopService;
use Closure;
use Illuminate\Http\Request;


class ShopStatusOrderAuth
{
    /**
     * Check Header Id [shopId, brandId]
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string|null ...$guards
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $shopId = $request->header('shopId');

        $shopInfo = ShopService::getShopAllStatus($shopId);
        if (empty($shopInfo)) {
            throw new ShopException(ShopCodeEnum::ERR_SHOP_ID_NO_EXIST);
        }
        // 判断 店铺营业状态
        if ($shopInfo['isBusiness'] == CodeEnum::SHOP_BUSINESS_STATUS_SUSPEND) {
            throw new OrderException(OrderCodeEnum::ERR_ORDER_SHOP_STATUS_IS_NOT);
        }

        // 判断是否传了渠道 ID
        $deliveryAddress = $request->get('deliveryAddress');
        if (empty($deliveryAddress['distributionId'])) {
            // 判断 小程序营业状态
            if ($shopInfo['appletStatus'] == CodeEnum::SHOP_APPLET_STATUS_SUSPEND) {
                throw new OrderException(OrderCodeEnum::ERR_ORDER_SHOP_APPLET_STATUS_IS_NOT);
            }
        }

        if (!isTest() && !PosOnlineService::checkPosOnline($shopId)) {
            throw new OrderException(OrderCodeEnum::ERR_POS_OFFLINE_STATUS);
        }

        return $next($request);
    }
}
